import os.path as opa

def zipfile(src_path, tgt_path, excludedFileType=[]):
    import zipfile, os
    path = opa.abspath(src_path)
    tgt_path = opa.abspath(tgt_path)

    with zipfile.ZipFile( tgt_path, 'w' ,zipfile.ZIP_DEFLATED ) as zipw:    
        for (aroot, dirlist, filelist) in os.walk(path):
            for afile in filelist:
                if (opa.splitext(afile)[1] in excludedFileType): continue
                srcFilePath = opa.abspath( opa.join(aroot, afile) )
                zipw.write(srcFilePath, opa.relpath(srcFilePath, path))


def parseArgs():

    from optparse import OptionParser
    #from optparse.OptionParser import *

    usage = "usage %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-t", "--target", action="store", type="string", dest="dirname", help="target directory")
    parser.add_option("-f", "--file", action="store", type="string", dest="filename", help="zip file path"),
    parser.add_option("-b", "--bin", action="store_false", dest="binary_mode", help="binary file included only")

    (options,args)=parser.parse_args()
    import os
    package_path = options.dirname if options.dirname != None else os.curdir
    package_path = opa.abspath(package_path)
    file_path = options.filename if options.filename != None else opa.join(package_path, "..", opa.split(package_path)[-1] + ".zip")
    file_path = opa.abspath(file_path)
    
    return package_path, file_path, options.binary_mode != None

if __name__ == "__main__":
    
    package_path, file_path, bin_mode = parseArgs()

    excludedFileType = []
    if bin_mode == False : excludedFileType += [".pyc", ".pyo"]
    else:
        excludedFileType += [".py"]
        import compileall
        compileall.compile_dir(package_path)
    zipfile(package_path, file_path, excludedFileType=excludedFileType)
